package com.atguigu.gmall.order.api;


import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.enums.OrderStatus;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.order.service.OrderDetailService;
import com.atguigu.gmall.order.service.OrderService;
import com.atguigu.gmall.order.to.OrderSplitTo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort.Order;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RequestMapping("/api/order")
@RestController
public class OrderController {


    @Autowired
    OrderService orderService;

    @Autowired
    OrderDetailService orderDetailService;

    /**
     * 库存系统在进行库存扣减需要的时候会给我们发送拆单逻辑
     *
     * @return 返回子订单的集合
     */
    @PostMapping("/orderSplit")
    public List<OrderSplitTo> orderSplit(@RequestParam("orderId") Long orderId,
                                         @RequestParam("wareSkuMap") String wareSkuMap) throws JsonProcessingException {

        //TODO 处理拆单 [{"wareId":"1","skuIds":["2","10"]},{"wareId":"2","skuIds":["3"]}]

        return orderService.splitOrder(orderId,wareSkuMap);
    }



    @GetMapping("/orderinfo/details/{outTradeNo}")
    public OrderInfo getOrderInfoWithDetailsByOutTradeNo(@PathVariable("outTradeNo") String outTradeNo){
        return orderService.getOrderInfoWithDetailsByOutTradeNo(outTradeNo);
    }


    @GetMapping("/auth/{PageNo}/{pageSize}")
    public Result getOrdersByPage(@PathVariable("/pageNo") Integer pageNo,
                                  @PathVariable("/pageSize")Integer pageSize,
                                  HttpServletRequest request){

        //获取当前用户id
        String userId = AuthContextHolder.getUserId(request);
        //查询当前用户的
        Page<OrderInfo> page = new Page<>(pageNo,pageSize); //分页对象
        QueryWrapper<OrderInfo> querywrapper = new QueryWrapper<>();
        querywrapper.eq("user_id",userId);
        Page<OrderInfo> infoPage = orderService.page(page, querywrapper);
        querywrapper.orderByDesc("id");
        List<OrderInfo> records = infoPage.getRecords();
        for (OrderInfo record : records) {

            QueryWrapper<OrderDetail> wrapper = new QueryWrapper<>();
            wrapper.eq("order_id",record.getId());
            List<OrderDetail> list = orderDetailService.list(wrapper);
            record.setOrderDetailList(list);
        }
        return Result.ok(infoPage);
    }

    /***
     * 把订单状态改成已支付
     * @param outTradeNo
     * @return
     */
    @GetMapping("/payed/success")
    public String changeOrderStatusPayed(@RequestParam("outTradeNo") String outTradeNo){
        orderService.changeOrderStatusPayed(outTradeNo, OrderStatus.PAID.name());
        return "ok";
    }


    @GetMapping("/getorder/{id}")
    public OrderInfo getOrderById(@PathVariable("id") Long orderId){
        OrderInfo byId = orderService.getById(orderId);

        return byId;
    }

    /**
     *                  consignee:收货人
     * 					consigneeTel: 收货人电话
     * 					deliveryAddress:收货地址
     * 					paymentWay:'ONLINE',
     * 					orderComment:'',
     * 					orderDetailList:[[${detailArrayList}]]
     * @param tradeNo 防重令牌
     * @param orderInfo 前端提交的相关数据
     * @return
     */

    @PostMapping("/auth/submitOrder")
    public Result submitOrder(@RequestParam(value = "tradeNo",required = true) String tradeNo,
                              @RequestBody OrderInfo orderInfo,
                              HttpServletRequest request){

        String userId = AuthContextHolder.getUserId(request);

        //1、TODO 先验证令牌 tradeNo
        if (!orderService.checkToken(userId,tradeNo)){
            //验证失败
            return Result.build(null, ResultCodeEnum.REPEAT_SUBMIT);
        }


        //TODO 哪些商品的价格发生变动，让前端重新确认（页面刷新一下，显示新价格，如果用户接受就继续提交）

        // TODO 验价; 把前端提交来的订单价格和当前商品真的价格进行对比
        //以下用来验价，验价遍历之后，当商品发生错误的时候用来提示消息(errMsg)
        List<OrderDetail> list = orderInfo.getOrderDetailList();
        //验证价格同时验证库存
        ArrayList<String> errMsg = orderService.checkSkuPriceAndStock(list);
        if (!CollectionUtils.isEmpty(errMsg)){
            //前面的验证失败
            Result<Object> fail = Result.fail();
            String join = String.join(",", errMsg);
            fail.setMessage(join);
            return fail;
        }

        //用户id
        orderInfo.setUserId(Long.parseLong(userId)); //往下传递用户id
        //前置校验通过，生成订单
        OrderInfo createOrder = orderService.createOrder(orderInfo);
        //订单id怎么生成，直接有工具类，普通的id生成办法
        Long id = orderInfo.getId(); //假装为雪花后的id

        return Result.ok(id);

    }
}
